package com.example.gokchinesefoodmapmcdev.handler;

import com.example.gokchinesefoodmapmcdev.util.JWTUtils;
import com.example.gokchinesefoodmapmcdev.util.ResultData;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义登录成功处理器
 */
@Component
public class MyLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JWTUtils jwtUtils;

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    /**
     * 用户登录成功后，需要生成cookie存放JWT token，发送至前端
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf8");
        /*
            登录成功后，
                1. 将存放在authentication中的用户信息和权限信息取出，作为用户权限作为payload传入，生成token字符串。
                2. 生成cookie传给前端
         */
        // 用户信息
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        // 权限信息，注意处理成String[]类型，只存角色名，否则在取值时取不到
        Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>) authentication.getAuthorities();
        String[] roles = new String[authorities.size()];
        int i = 0;
        for (GrantedAuthority authority : authorities) {
            roles[i] = authority.getAuthority();
            i++;
        }

        Map<String, Object> payloadInfo = new HashMap<>();
        payloadInfo.put("username", userDetails.getUsername());
        payloadInfo.put("roles", roles);
        // 生成token
        String token = jwtUtils.createToken(payloadInfo, 1800);

        // 生成cookie发送出去
        Cookie cookie = new Cookie("token", token);
        cookie.setMaxAge(1800);
        response.addCookie(cookie);

        // 登录成功，返回给前端JSON格式字符串
        ResultData resultData = new ResultData();
        resultData.put("code", ResultData.VERIFY_SUCCESS);
        resultData.put("msg", "验证成功");
        resultData.put("token", token);
        response.getWriter().println(new ObjectMapper().writeValueAsString(resultData));

    }
}
